package cn.hotel.utlis;

import java.sql.*;
import java.util.List;

public class Crud {
    private final Read read = Read.getRead();
    private final String URL = read.getString("jdbc.URL");
    private final String USER = read.getString("jdbc.USER");
    private final String PASSWORD = read.getString("jdbc.PASSWORD");
    private final String CONNECT  = read.getString("jdbc.CONNECT");

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    //封装加载驱动和数据库连接
    private Connection getConnection(){
        try {
            Class.forName(CONNECT);
            connection = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    //封装增删改
    public int getInt(String sql, List<Object> data){
        this.getConnection();
        int num = 0;
        try {
            //开启事务
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);
            if(data != null && data.size() > 0){
                for (int i = 0; i < data.size(); i++) {
                    preparedStatement.setObject((i+1),data.get(i));
                }
            }

            num = preparedStatement.executeUpdate();
            //提交事务
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            try {
                //回滚事务
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }finally {
            this.setClear(null);
        }
        return num;
    }
    //封装查询
    public ResultSet getResultSet(String sql,List<Object> data){
        this.getConnection();
        try {
            preparedStatement = connection.prepareStatement(sql);
            if(data != null && data.size() >0){
                for (int i = 0; i < data.size(); i++) {
                    preparedStatement.setObject((i+1),data.get(i));
                }
            }
            resultSet = preparedStatement.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }
    //封装缓存清理
    public void setClear(ResultSet resultSet){
        try {
            if (resultSet != null){
                resultSet.close();
            }
            preparedStatement.close();
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
